package com.lanou.musicproject.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.musicproject.R;
import com.lanou.musicproject.activity.RankMatter;
import com.lanou.musicproject.adapter.RankListViewAdapter;
import com.lanou.musicproject.bean.Rank;
import com.lanou.musicproject.volley.VolleySingleton;

import org.json.JSONObject;

import java.util.List;


/**
 * 排行榜
 * Created by dllo on 15/10/20.
 */

public class RankFragment extends Fragment implements AdapterView.OnItemClickListener {
    private ListView rank_ListView ;
    private List <Rank.ContentEntity> data;
    private String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting." +
            "billboard.billCategory&format=json&kflag=1";
    private RankListViewAdapter adapter;
    private VolleySingleton volleySingleton;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rank_fragment,null);
        rank_ListView= (ListView) view.findViewById(R.id.rank_ListView);
        rank_ListView.setOnItemClickListener(RankFragment.this);
        initData();

        return view;
    }

    private void initData() {
        volleySingleton= VolleySingleton.getInstance(getActivity());
        JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                String str = response.toString();
                Rank rank= JSON.parseObject(str,Rank.class);
                data= rank.getContent();
                adapter= new RankListViewAdapter(getActivity(),data);
                rank_ListView.setAdapter(adapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(jr);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Rank.ContentEntity entity;
        entity = (Rank.ContentEntity) parent.getItemAtPosition(position);
        if (entity.getType() != null){
            Intent intent = new Intent(getActivity()
                    , RankMatter.class);
            intent.putExtra("type",entity);
            startActivity(intent);
        }
    }

}
